def month_before(a_time)
    a_time - 28 * 24 * 60 * 60
end

def header(first_date, second_date)
    #date.strftime("Changes since %Y-%m-%d:")
    "Changes between #{first_date} and #{second_date}:"
end

def subsystem_line(subsystem_name, count_change)
    if count_change == 0
        "#{subsystem_name.ljust(14)}#{"-".ljust(20)}#{"-".ljust(20)}"
    elsif 0 < count_change && count_change <= 2
        "#{subsystem_name.ljust(14)}"+"(#{count_change} changes)".ljust(20)+"*".ljust(20)
    else
	"#{subsystem_name.ljust(14)}"+"(#{count_change} changes)".ljust(20)+"#{stars(count_change)}".ljust(20)
    end
end

def stars(number_of_changes)
    "*"*((number_of_changes/5.0).round)
end

def number_of_changes(subfolder_name, start_date, end_date)
    extract_number_of_changes(get_svn_log(subfolder_name, start_date, end_date))
end

def extract_number_of_changes(text)
    lines = text.split("\n")
    dashed_lines = lines.find_all {|line| line.include?("----")}
    dashed_lines.length-1
end

def get_svn_log(subsystem, start_date, end_date)
    timespan = "--revision {#{start_date}}:{#{end_date}}"
    path = "svn://rubyforge.org/var/svn/churn-demo"

    `svn log #{timespan} #{path}/#{subsystem}`
end

def get_count_from_line(subsystem_line)
    if /\(\d+ changes\)/ =~ subsystem_line
	/\((\d+)/.match(subsystem_line)[1].to_i
    else 0
    end
end

def order_subsystem_line(subsystem_line)
    subsystem_line.sort do |one, another|
	number_one = get_count_from_line(one)
	number_another = get_count_from_line(another)
	-( number_one <=> number_another)
    end
end


def show_query_output(system_names, start_date, end_date)
    puts header(start_date, end_date)
    lines = system_names.collect do |subsystem|
    subsystem_line(subsystem, number_of_changes(subsystem, start_date, end_date))
    end
    puts order_subsystem_line(lines)
end

if $0 == __FILE__
#start_date = month_before(Time.now)

#start_date = Time.local(2004,07,30)

system_names = ['audit', 'fulfillment','persistence', 'ui', 'util', 'inventory']

if ARGV.length == 2 #between first date and second date
   start_date = ARGV[0]
   end_date = ARGV[1]
   show_query_output(system_names, start_date, end_date)
elsif ARGV.length == 1 #from the date to today
   start_date = ARGV[0]
   end_date = Time.now.strftime("%Y-%m-%d")
   show_query_output(system_names, start_date, end_date)
elsif ARGV.length == 0 #from today to one month before
   start_date = month_before(Time.now).strftime("%Y-%m-%d")
   end_date = Time.now.strftime("%Y-%m-%d")
   show_query_output(system_names, start_date, end_date)
else puts "Usage: 0-2 parameters required."
end

end
